package models;

import java.util.Date;
import java.util.List;

import dto.NodeDto;

import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;
import siena.Table;
import util.Util;

@Table("category_node")
public class CategoryNode extends Model{

	@Id(Generator.AUTO_INCREMENT)
	public Long id;
	
	public long parentId;
	public String type;
	public String title;
	public int left;
	public int right;
	public int position;
	public String alias;
	
	public CategoryNode(String title) {
		this.title = title;
		this.alias = Util.convertUTF8TOASCII(title);
	}
	
	static Query<CategoryNode> all(){
		return Model.all(CategoryNode.class);
	}
	
	public static List<CategoryNode> listCategory(){
		return all().fetch();
	}

	/**
	 * @param page
	 * @param limit
	 * @return
	 */
	public static List<CategoryNode> findByLimit(int page, int limit) {
		return all().fetch(limit, (page - 1) * Util.PAGE_ITEM);
	}
	
	public static CategoryNode findById(Long id){
		return all().filter("id", id).get();
	}
	
	public static CategoryNode find(String alias){
		return all().filter("alias", alias).get();
	}
	
	public static CategoryNode find(long id) {
		return Model.getByKey(CategoryNode.class, id);
	}
	
	public static List<CategoryNode> load(long parent) {
		return Model.all(CategoryNode.class).filter("parentId", parent).order("position").fetch();
	}

	public static List<CategoryNode> rootChild() {
		List<CategoryNode> nodes = load(0);
		if(nodes != null && !nodes.isEmpty()) {
			long parent = nodes.get(0).id;
			return load(parent);
		}
		return null;
	}
}
